const sqlite3 = require('sqlite3').verbose();
const path = require('path');

const dbPath = path.join(__dirname, 'data', 'pph.sqlite');
const db = new sqlite3.Database(dbPath);

console.log('🎯 检查PPH目标值和预估值数据...');

// 检查目标值表
db.all("SELECT COUNT(*) as count FROM pph_targets", (err, rows) => {
    if (err) {
        console.error('❌ 查询目标值表失败:', err);
    } else {
        console.log(`📊 PPH目标值记录总数: ${rows[0].count}`);
        
        if (rows[0].count > 0) {
            // 显示前几条目标值记录
            db.all("SELECT material_code, line_name, record_date, whole_machine_target, motor_target, is_whole_machine FROM pph_targets ORDER BY record_date DESC LIMIT 5", (err2, targetRows) => {
                if (!err2) {
                    console.log('\n🎯 最新5条目标值记录:');
                    targetRows.forEach((row, i) => {
                        const target = row.is_whole_machine ? row.whole_machine_target : row.motor_target;
                        console.log(`  ${i+1}. ${row.material_code} @ ${row.line_name} (${row.record_date}) = ${target} PPH`);
                    });
                }
            });
        }
    }
});

// 检查预估值表
db.all("SELECT COUNT(*) as count FROM pph_estimates", (err, rows) => {
    if (err) {
        console.error('❌ 查询预估值表失败:', err);
    } else {
        console.log(`\n📈 PPH预估值记录总数: ${rows[0].count}`);
        
        if (rows[0].count > 0) {
            // 显示前几条预估值记录
            db.all("SELECT material_code, line_name, estimate_pph FROM pph_estimates ORDER BY updated_at DESC LIMIT 5", (err2, estimateRows) => {
                if (!err2) {
                    console.log('\n📈 最新5条预估值记录:');
                    estimateRows.forEach((row, i) => {
                        console.log(`  ${i+1}. ${row.material_code} @ ${row.line_name} = ${row.estimate_pph} PPH`);
                    });
                }
            });
        }
    }
    
    // 检查最新PPH记录的目标值字段
    db.all("SELECT id, material_code, line_name, record_date, target_pph, estimate_pph, efficiency_rate FROM pph_records ORDER BY id DESC LIMIT 3", (err3, recordRows) => {
        if (!err3) {
            console.log('\n📝 最新3条PPH记录的目标值字段:');
            recordRows.forEach((row, i) => {
                console.log(`  ${i+1}. ID=${row.id}: ${row.material_code} @ ${row.line_name} (${row.record_date})`);
                console.log(`     目标PPH: ${row.target_pph}, 预估PPH: ${row.estimate_pph}, 达成率: ${row.efficiency_rate}%`);
            });
        }
        db.close();
    });
});
